<template>
  <div class="category-page">
    <!-- 导航栏 -->
    <van-nav-bar title="分类" />
    <!-- 新增搜索框区域 -->
    <div class="search-container">
      <van-search v-model="searchValue" placeholder="请输入商品名称搜索" @search="handleSearch" @focus="handleSearchFocus" />
    </div>
    <!-- 分类与商品展示区域 -->
    <div class="category-container">
      <!-- 左侧一级分类 -->
      <div class="level-1-category">
        <van-cell-group>
          <van-cell v-for="(level1, index) in level1Categories" :key="level1.id" :title="level1.name"
            :class="{ active: activeLevel1Index === index }" @click="handleLevel1Click(index, level1)" />
        </van-cell-group>
      </div>

      <!-- 右侧商品列表 -->
      <div class="right-products">
        <!-- 二级分类 -->
        <div class="level-2-category">
          <van-cell-group>
            <van-cell v-for="(level2, index) in currentLevel2Categories" :key="level2.id" :title="level2.name"
              :class="{ active: activeLevel2Id === level2.id }" @click="handleLevel2Click(level2.id)" />
          </van-cell-group>
        </div>
        <!-- 商品列表区域 -->
        <div class="product-list">
          <van-card v-for="product in products" :key="product.id" :title="product.name" :price="product.price"
            :thumb="product.image_url" class="product-card" @click="goToProductDetail(product.id)">
            <template #footer>
              <van-button class="custom-add-to-cart" size="mini" type="primary" @click="addToCart(product)">
                加入购物车
              </van-button>
            </template>
          </van-card>
        </div>

        <!-- 空状态提示 -->
        <van-empty v-if="products.length === 0 && categories.length > 0" description="暂无商品" />
      </div>
    </div>

    <!-- 底部导航栏 -->
    <Button></Button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast } from 'vant';
import Button from '@/components/Button.vue';
import api from '@/api/history';
import { recordBrowse } from '@/api/history';
// 响应式数据
const router = useRouter(); // 路由
const categories = ref([]); // 所有分类列表
const products = ref([]); // 当前分类下的商品列表
const level1Categories = ref([]); // 一级分类列表
const currentLevel2Categories = ref([]); // 当前一级分类下的二级分类
const activeLevel1Index = ref(0); // 选中的一级分类索引
const activeLevel2Id = ref(null); // 选中的二级分类ID
const route = useRoute();
const searchValue = ref('');
// 初始化页面
onMounted(async () => {
  // 加载分类数据
  await fetchLevel1Categories();
});

// 获取一级分类（包含二级分类）
const fetchLevel1Categories = async () => {
  try {
    const response = await api.get('/products/secondary_categories');
    level1Categories.value = response.data;
    // 初始化默认选中第一个一级分类的第一个二级分类
    if (level1Categories.value.length > 0) {
      const firstLevel1 = level1Categories.value[0];
      currentLevel2Categories.value = firstLevel1.children || [];
      if (currentLevel2Categories.value.length > 0) {
        activeLevel2Id.value = currentLevel2Categories.value[0].id;
        await fetchProductsByCategory(activeLevel2Id.value);
      }
    }
  } catch (error) {
    showToast('获取分类失败');
    console.log('分类数据获取失败:', error);
  }
};

// 根据分类ID获取商品列表
const fetchProductsByCategory = async (categoryId) => {
  try {
    const response = await api.get(`/products/products_by_category/${categoryId}`);
    products.value = response.data;
  } catch (error) {
    console.error('获取商品数据失败:', error);
  }
};

// 切换一级分类
const handleLevel1Click = (index, level1) => {
  activeLevel1Index.value = index;
  currentLevel2Categories.value = level1.children || [];
  if (currentLevel2Categories.value.length > 0) {
    activeLevel2Id.value = currentLevel2Categories.value[0].id;
    fetchProductsByCategory(activeLevel2Id.value);
  } else {
    products.value = [];
  }
};

// 切换二级分类
const handleLevel2Click = (categoryId) => {
  activeLevel2Id.value = categoryId;
  fetchProductsByCategory(categoryId);
};

// 加入购物车
const addToCart = (product) => {
  showToast(`${product.name} 已加入购物车`);
};

const goToProductDetail = async (productId) => {
  try {
    const userId = 1 || route.params.userId; 
    await recordBrowse(userId, productId); 
    console.log(`已记录商品[${productId}]的浏览历史`);
  } catch (error) {
    console.log('记录浏览历史失败（不影响跳转）:', error);
  } finally {
    router.push({ name: 'ProductDetail', params: { id: productId } });
  }
};

// 处理搜索框聚焦事件 - 点击搜索框直接跳转
const handleSearchFocus = () => {
  // 如果已有输入内容，携带参数跳转
  router.push({
    name: 'productsearch',
    query: { keyword: searchValue.value.trim() }
  });
};

// 处理搜索事件 - 输入完成后点击搜索按钮跳转
const handleSearch = () => {
  if (!searchValue.value.trim()) {
    showToast('请输入搜索关键词');
    return;
  }

  router.push({
    name: 'productsearch',
    query: { keyword: searchValue.value.trim() }
  });
};
</script>


<style scoped>
.category-container {
  display: flex;
  height: calc(100vh - 46px - 50px);
  overflow: hidden;
}
/* 左侧分类样式 */
.left-category {
  width: 30%;
  height: 100%;
  overflow-y: auto;
  background-color: #a3b0a7;
}

.level-1-category {
  display: flex;
  flex-direction: column;
  background-color: #f3f3f5;
}

.left-category .van-cell {
  justify-content: center;
  font-size: 10px;
  padding: 15px 0;
}

.left-category .active {
  font-weight: bold;
  margin-right: 10px;
}

/* 右侧商品样式 */
.right-products {
  width: 70%;
  height: 100%;
  overflow-y: auto;
  padding: 10px;
}

.product-list {
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.product-card {
  font-size: 10px;
}

/* 二级分类样式（核心调整，匹配图片紧凑效果） */
.level-2-category {
  display: flex;
  overflow-x: auto;
  padding: 5px 0;
  margin-bottom: 10px;
  /* 与下方商品区域的间距 */
}

/* 去除van-cell-group默认样式干扰 */
.level-2-category .van-cell-group {
  display: flex;
  width: 100%;
}

/* 二级分类选项样式（匹配图片中"智能手机"等紧凑排列） */
.level-2-category .van-cell {
  /* 横向紧凑排列 */
  display: inline-flex;
  padding: 4px 12px;
  margin: 0 4px;
  font-size: 12px;
  background: transparent;
  border: none;
  letter-spacing: -0.8px;
}

/* 选中状态样式（突出当前分类） */
.level-2-category .van-cell.active {
  font-weight: bold;
  padding-bottom: 2px;
}

/* 自定义加入购物车按钮颜色 */
.custom-add-to-cart {
  background-color: #ff6b00;
  border-color: #ff6b00;
}
</style>